package com.MyRealm;

import com.dao.RoleMapper;
import com.dao.UserMapper;
import com.model.Role;
import com.model.User;
import com.util.ActiveUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName MyRealm
 * @Description 自定义的reaml类   实现用户认证和授权
 * @Author ss
 * @Date 2020/7/28 10:56
 * @Version 1.0
 */
public class MyRealm extends AuthorizingRealm {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RoleMapper roleMapper;
    //用户授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        ActiveUser activerUser=(ActiveUser) principals.getPrimaryPrincipal();
        List<String> roles = activerUser.getRoleList();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if(null!=roles&& roles.size()>0) {
            info.addRoles(roles);
        }
        return info;
    }

    //用户认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = token.getPrincipal().toString();
        ActiveUser activerUser=new ActiveUser();
        // 根据用户名查询用户对象
        User user = this.userMapper.queryUserByUserName(username);
        if (null != user) {
            activerUser.setUser(user);
            List<Role> roles=roleMapper.queryRoleByUserId(user.getUserid());
            List<String> roleList=new ArrayList<>();
            for(Role role:roles){
                roleList.add(role.getDes());
            }
            activerUser.setRoleList(roleList);
            ByteSource credentialsSalt = ByteSource.Util.bytes(user.getUsername());
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(activerUser, user.getPassword(), credentialsSalt, getName());
            return info;
        }
        return null;
    }

    public static void main(String[] args) {
        //加密测试代码
        //设置加密方式
        String algorithmName = "MD5";
        //设置待加密的原密码
        Object source = "123";
        //设置加盐方式(一般来说都是以用户名来加盐)
        Object salt = ByteSource.Util.bytes("user");
        /* 加密次数 */
        int hashIterations = 1024;
        SimpleHash newPassword = new SimpleHash(algorithmName, source, salt, hashIterations);
        System.out.println(newPassword.toString());
    }
}
